package com.gcloud.mesh.monitor.timer;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.asset.dao.IaasDao;
import com.gcloud.mesh.asset.enums.DeviceType;
import com.gcloud.mesh.header.vo.asset.DeviceItemVo;
import com.gcloud.mesh.header.vo.supplier.DaHuaSupervisionSystemVo;
import com.gcloud.mesh.monitor.dao.StatisticsDao;
import com.gcloud.mesh.monitor.entity.StatisticsEntity;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.entity.SupplierEntity;
import com.gcloud.mesh.utils.SupplierSystemTypeUtil;

import lombok.extern.slf4j.Slf4j;

@Component
@Slf4j
public class DaHuaEnvirommentTimer {

	@Autowired
	StatisticsDao statisticsDao;

	@Autowired
	private IaasDao iaasDao;

	@Autowired
	private SupplierDao supplierDao;

	private static final String TYPE = "supervision_system_dahua";

	private static final String queryAllDeviceInfoAction = "/xtjk/webService/queryAllDeviceInfo.action";

	private static final String queryCollectDataAction = "/xtjk/webService/queryCollectData.action";
	
	private Map<String, String> values = new HashMap<String, String>();
	
	private static Map<String, String> metrics = new HashMap<String, String>();
	
	private static Map<String, String> devices = new HashMap<String, String>();
	
	static {
		
		//TODO 补充大华动环指标
		metrics.put("平均回风温度", "environment.air_in_temperature"); // 温湿度_温度
		metrics.put("平均回风湿度", "environment.air_in_humidity"); // 温湿度_湿度
	}

	@Scheduled(fixedDelay = 1000 * 60 * 5)
	public void work() {

		List<SupplierEntity> suppliers = supplierDao.findAll().stream().filter(s -> TYPE.equals(s.getType()))
				.collect(Collectors.toList());
		for (SupplierEntity supplier : suppliers) {

			DaHuaSupervisionSystemVo obj = (DaHuaSupervisionSystemVo) SupplierSystemTypeUtil
					.getByName(supplier.getType(), supplier.getConfig());

			String hostIp = obj.getHostIp();
			String port = obj.getPort();

			this.getDevices(hostIp, port);
			this.getData(hostIp, port);
			
			if (values != null && values.size() > 0) {
				for (String key : metrics.keySet()) {
					StatisticsEntity entity = new StatisticsEntity();
					entity.setId(UUID.randomUUID().toString());
					entity.setMeter(metrics.get(key));

					entity.setTimestamp(new Date());
					entity.setValue(Double.valueOf(values.get(key)));

					if (entity.getMeter().contains("air")) {
						List<DeviceItemVo> items = iaasDao.listDevice(supplier.getDatacenterId(), DeviceType.AIR_CONDITION.getNo());
						for (DeviceItemVo item : items){
							if(item.getDeviceId().equals(devices.get("air"))){
								entity.setResourceId(item.getId());
							}
						}
					} else if (entity.getMeter().contains("ups")) {
						List<DeviceItemVo> items = iaasDao.listDevice(supplier.getDatacenterId(), DeviceType.UPS.getNo());
						for (DeviceItemVo item : items){
							if(item.getDeviceId().equals(devices.get("ups"))){
								entity.setResourceId(item.getId());
							}
						}
					}
					statisticsDao.save(entity);
				}
			}else {
				log.debug("[DaHuaEnvironmentTimer] 未采集到动环数据!");
			}
		}
	}

	private void getDevices(String hostIp, String port) {
		String url = "http://" + hostIp + ":" + port + queryAllDeviceInfoAction;
		RestTemplate restTemplate = new RestTemplate();
		String res = restTemplate.getForEntity(url, String.class).getBody();
		JSONObject resJ = JSONObject.parseObject(res);
		JSONArray jsonArray = resJ.getJSONArray("rows");
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject json = jsonArray.getJSONObject(i);
			if (json.getString("deviceName").contains("温湿度")) {
				devices.put("air", json.getInteger("id").toString());
			} else if (json.getString("deviceName").contains("UPS")) { // ups的设备类型未得知
				devices.put("ups", json.getInteger("id").toString());
			}
		}
	}

	private void getData(String hostIp, String port) {

		String url = "http://" + hostIp + ":" + port + queryCollectDataAction;
		RestTemplate restTemplate = new RestTemplate();
		String res = restTemplate.getForEntity(url, String.class).getBody();
		JSONObject resJ = JSONObject.parseObject(res);
		JSONArray jsonArray = resJ.getJSONArray("rows");
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject json = jsonArray.getJSONObject(i);
			values.put(json.getString("paramName"), json.getString("collectionData"));
		}
	}
}
